package com.warm.androidstudy.view.liveData;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.BindingAdapter;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.Observable;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.warm.androidstudy.BR;
import com.warm.androidstudy.view.liveData.model.NameViewModel;
import com.warm.androidstudy.R;
import com.warm.androidstudy.databinding.ActivityLiveDataBinding;
import com.warm.androidstudy.view.liveData.adapter.NameAdapter;
import com.warm.androidstudy.view.liveData.model.Dog;
import com.warm.androidstudy.view.liveData.model.Human;
import com.warm.androidstudy.view.liveData.model.TestBean;
import com.warm.androidstudy.view.liveData.model.User;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import static com.bumptech.glide.load.resource.bitmap.BitmapTransitionOptions.withCrossFade;

/**
 * @author DELL
 */
public class LiveDataActivity extends AppCompatActivity implements View.OnClickListener {
    private NameViewModel nameViewModel;
    private Button add;
    private Button current;
    private TextView textView;
    private RecyclerView recyclerView;
    private NameAdapter nameAdapter;
    private ActivityLiveDataBinding binding;
    private Dog dog;
    private List<String> nameList = new ArrayList<>();
    private ObservableList<String> list = new ObservableArrayList<>();
    private Human human;
    private MutableLiveData<String> liveData = new MutableLiveData<>();

    private TestBean testBean = new TestBean();

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_live_data);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_live_data);
        User user = new User("sam",11,false);
        dog = new Dog("HHH","#FFFDDD");
        binding.setUser(user);
        binding.setDog(dog);
//        binding.viewStub.getViewStub().inflate();
//        binding.setUser(user);
        human = new Human("123",1);
        binding.setHuman(human);
//        ObservableArrayMap<String, Object> user2 = new ObservableArrayMap<>();
//        user2.put("name", "Jack");
//        user2.put("age", 2);
//        binding.setUser(user2);

        binding.setOnlyLive(liveData.getValue());
        binding.setDataBsource(testBean);
        addTextViewChange();


        liveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                binding.setOnlyLive(s);
                Log.e("观察LiveData", "单独使用LiveData ==> " + s);
            }
        });


        nameAdapter = new NameAdapter(R.layout.adapter_name);
        binding.rvData.setLayoutManager(new LinearLayoutManager(this));
        binding.rvData.setAdapter(nameAdapter);
        binding.btnAdd.setOnClickListener(this);
        binding.btnCurrent.setOnClickListener(this);
        nameViewModel = ViewModelProviders.of(this).get(NameViewModel.class);
        nameViewModel.getmCurrentName().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String name) {
                binding.tvText.setText(name);
            }
        });
        // 订阅LiveData中Name列表数据变化，以lambda形式定义Observer
        nameViewModel.getmNameList().observe(this, new Observer<List<String>>() {
            @Override
            public void onChanged(List<String> nameList) {
                if (nameList!=null){
                    nameAdapter.setNewData(nameList);
                    nameAdapter.notifyDataSetChanged();
                }else {
                    Log.e("gsm","空");
                }

            }
        });
    }

    private void addTextViewChange(){
        binding.txtOnlyLive.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.e("TextView的变化", "单独使用LiveData ==> " + s);
            }
        });
        binding.txtDataBinding.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.e("TextView的变化", "DataBinding双向绑定 ==> " + s);
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        liveData.postValue("单独LiveData使用");
        testBean.name.set("我是DataBinding双向绑定");
    }

    @Override
    public void onClick(View v) {
        int randowInt = new Random().nextInt(100);
        switch (v.getId()){
            case R.id.btn_add:
                for (int i = 0; i < 10; i++) {
                    nameList.add("gsm:<"+i+">");
                }
                nameViewModel.getmNameList().setValue(nameList);

                break;
            case R.id.btn_current:
                nameViewModel.getmCurrentName().setValue(String.valueOf(Math.random()*10));
                dog = new Dog("8888","#FFFDDD");
                binding.setDog(dog);
                human.name.set("玉玑子");
                human.age.set(15);
                binding.setHuman(human);
                dog.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
                    @Override
                    public void onPropertyChanged(Observable sender, int propertyId) {
                        if (propertyId == BR.docName) {
                            Log.e("看看刷新了哪", "刷新了name");
                        } else if (propertyId == BR._all) {
                            Log.e("看看刷新了哪", "所有所有");
                        } else {
                            Log.e("看看刷新了哪", "未知错误~");
                        }
                    }
                });

                //改变list的第一项
                list.add(0,"list的值" + randowInt);
                list.add(1,"list2的值" + randowInt);
                binding.setList(list);
                loadImage(binding.ivImg,"https://img1.baidu.com/it/u=3443981983,2078999032&fm=26&fmt=auto&gp=0.jpg");


                break;
            default:
                break;
        }
    }

    @BindingAdapter("imageWithGlide")
    public static void loadImage(ImageView imageView, String url) {
        Glide.with(imageView).load(url)
                .apply(new RequestOptions().placeholder(R.mipmap.ic_launcher))
                .into(imageView);
    }
}
